<?php

namespace app\common\model\xiluhouse;

use think\Model;

class FollowLog extends Model
{

    // 表名
    protected $name = 'xiluhouse_follow_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $err_msg = '';
    // 追加属性
    protected $append = [
        'images_arr',
        'house_state_text',
        'audit_state_text',
        'checktime_text',
        'status_text',
    ];
    public function getImagesArrAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['images']) ? $data['images'] : '');
        $arr=$value ? explode(',', $value):[];
        foreach ($arr as $key => $v) {
            $arr[$key]=cdnurl($v,true);
        }
        return $arr;
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return time_tran($value);
    }

    public function getHouseStateList()
    {
        return ['0' => __('无意向'), '1' => __('待看房'), '2' => __('已看房'), '3' => __('已付订'), '4' => __('已签约'), '5' => __('已款清'), '6' => __('放弃客户')];
    }

    public function getAuditStateList()
    {
        return ['1' => __('Audit_state 1'), '2' => __('Audit_state 2'), '3' => __('Audit_state 3'), '4' => __('Audit_state 4')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }

    public function getHouseStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['house_state']) ? $data['house_state'] : '');
        $list = $this->getHouseStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getAuditStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['audit_state']) ? $data['audit_state'] : '');
        $list = $this->getAuditStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getChecktimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['checktime']) ? $data['checktime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setChecktimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function broker()
    {
        return $this->belongsTo('User', 'broker_user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 创建跟进记录
     * @param int    $appoint_log_id           无     关联预约订单
     * @param int    $house_state              无     购房状态:0=无意向(已流失),1=待看房,2=已看房,3=已付订,4=已签约,5=已款清,6=放弃客户
     * @param string $name                     无     跟进标题
     * @param string $discription              无     详细描述
     * @param string $dissatisfaction          无     不满意的描述
     * @param string $images                  无     证明多图
     * @param string $money                   无     成交金额
     */
    public function createNowLog($params)
    {
        if (!isset($params['house_state'])) {
            $this->err_msg = '状态错误';
            return false;
        }
        $exist = AppointLog::where('is_using', 2)->where('user_id', $params['user_id'])->where('state', 2)->where('rental_id', 0)->find();

        if (!$exist && $params['house_state'] != 1) {
            $this->err_msg = '不存在可修改状态的订单';
            return false;
        }
        if ($exist['id'] != $params['appoint_log_id']) {
            $this->err_msg = '参数错误';
            return false;
        }
        switch ($params['house_state']) {
            case 0:
                # 无意向(已流失)
                // 1、把该客户的所有订单状态改为不处理
                $res = AppointLog::where('user_id', $params['user_id'])->where('state', 2)->where('rental_id', 0)->update(['state' => 4, 'house_state' => 0, 'is_using' => 1, 'broker_user_id' => 0, 'audit_state' => 1]);
                if (!$res) {
                    $this->err_msg = '更新订单状态错误';
                    goto err;
                }
                // 2、改用户的状态
                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                if ($user_info['can_loss_state'] == 2) {
                    $this->err_msg = '后台已暂缓流失处理中，暂时无法修改为流失状态';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    'house_state' => 0,
                    'broker_user_id' => 0,
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '客户无意向';
                break;
            case 1:
                # 待看房(已分配经纪人)
                // 1、改用户的状态
                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    'house_state' => 1,
                    'broker_user_id' => $params['broker_user_id'],
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '分配咨询师';
                break;
            case 2:
                # 已看房
                if ($exist['house_state'] != 1) {
                    $this->err_msg = '状态错误';
                    return false;
                }
                $res = $exist->save(['state' => 2, 'house_state' => 2, 'audit_state' => 1]);
                if (!$res) {
                    $this->err_msg = '修改状态错误';
                    goto err;
                }
                // 1、改用户的状态
                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    'house_state' => 2,
                    'max_house_state' => $user_info['max_house_state'] < 2 ? 2 : $user_info['max_house_state'],
                    'broker_user_id' => $params['broker_user_id'],
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '客户已看房';
                break;
            case 3:
                # 已付订
                if ($exist['house_state'] != 2) {
                    $this->err_msg = '状态错误';
                    return false;
                }
                $res = $exist->save(['state' => 2, 'house_state' => 3, 'audit_state' => 1]);
                if (!$res) {
                    $this->err_msg = '修改状态错误';
                    goto err;
                }
                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    'house_state' => 3,
                    'max_house_state' => $user_info['max_house_state'] < 3 ? 3 : $user_info['max_house_state'],
                    'broker_user_id' => $params['broker_user_id'],
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '客户已付订';
                break;
            case 4:
                # 已签约
                if ($exist['house_state'] != 3) {
                    $this->err_msg = '状态错误';
                    return false;
                }
                $res = $exist->save(['state' => 2, 'house_state' => 4, 'audit_state' => 1]);
                if (!$res) {
                    $this->err_msg = '修改状态错误';
                    goto err;
                }
                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    'house_state' => 4,
                    'max_house_state' => $user_info['max_house_state'] < 4 ? 4 : $user_info['max_house_state'],
                    'broker_user_id' => $params['broker_user_id'],
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '客户已签约';
                break;
            case 5:
                # 已款清
                if ($exist['house_state'] != 4) {
                    $this->err_msg = '状态错误';
                    return false;
                }
                $res = $exist->save(['state' => 2, 'house_state' => 4, 'audit_state' => 2]);
                if (!$res) {
                    $this->err_msg = '修改状态错误';
                    goto err;
                }
                $params['audit_state'] = 2;

                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    // 'house_state'=>5,
                    // 'max_house_state'=>$user_info['max_house_state']<5?5:$user_info['max_house_state'],
                    // 'broker_user_id'=>$params['broker_user_id']
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '客户已款清';
                break;
            case 6:
                # 放弃客户
                if ($exist['house_state'] == 5 || ($exist['house_state'])) {
                    $this->err_msg = '状态错误';
                    return false;
                }
                // 1、把该客户的所有订单状态改为不处理
                $res = $this->where('user_id', $params['user_id'])->where('state', 2)->where('rental_id', 0)->update(['state' => 1, 'house_state' => 6, 'is_using' => 1, 'audit_state' => 1]);
                if (!$res) {
                    $this->err_msg = '修改状态错误';
                    goto err;
                }
                $user_info = UserProfile::where('user_id', $params['user_id'])->find();
                if (!$user_info) {
                    $this->err_msg = '查找不到该用户';
                    goto err;
                }
                $res = $user_info->save([
                    'followtime' => time(),
                    'house_state' => 6,
                    'broker_user_id' => $params['broker_user_id'],
                ]);
                $params['name'] = $params['name'] ? $params['name'] : '咨询师放弃客户';
                break;
            default:
                $this->err_msg = '状态错误';
                goto err;
                break;
        }
        $res = $this->allowField(true)->save($params);
        if (!$res) {
            $this->err_msg = '更新错误';
            goto err;
        }
        return true;
        err:
        return false;
    }
    /**
     * 获取最后产生的错误
     * @return string
     */
    public function nowError()
    {
        return $this->err_msg;
    }
}
